package com.sprouting.ops.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sprouting.ops.annotations.invoke.IdempotentSingle;
import com.sprouting.ops.interfaces.AddGroup;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.interfaces.UpdGroup;
import com.sprouting.ops.model.DromaraFileStorage;
import com.sprouting.ops.model.OpsComponentVersion;
import com.sprouting.ops.model.ResultJson;
import com.sprouting.ops.model.qo.OpsComponentVersionQo;
import com.sprouting.ops.service.DromaraFileStorageService;
import com.sprouting.ops.service.OpsComponentVersionService;
import com.sprouting.ops.utils.CheckTool;
import com.sprouting.ops.utils.EntityTool;
import com.sprouting.ops.utils.IdTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (组件版本信息表)表控制层
 *
 * @author longx
 * @since 2023-11-25 18:39:34
 */
@Slf4j
@RestController
@RequestMapping("opsComponentVersion")
public class OpsComponentVersionController {

    @Resource
    private OpsComponentVersionService opsComponentVersionService;
    @Resource
    private DromaraFileStorageService dromaraFileStorageService;


    // /**
    //  * 获取当前可以添加的组件版本
    //  * @param siteId 场所ID
    //  * @return
    //  */
    // @PostMapping("getSiteAddComponent")
    // public ResultJson getSiteAddComponent(String siteId){
    //     if (CheckTool.checkNull(siteId)){
    //         return ResultJson.errorCheck();
    //     }
    //
    //     List<OpsAppDeployVo> deployVoList = opsAppDeployService.getBySiteId(siteId);
    //     if (CollUtil.isEmpty(deployVoList)){
    //         return ResultJson.success();
    //     }
    //
    //     // 查询当前场所部署的项目应用
    //     List<String> appIdList = deployVoList.stream().map(OpsAppDeployVo::getAppId).collect(Collectors.toList());
    //     // 查询依赖的组件
    //     List<OpsComponentVersionVo> componentVersionList = opsComponentVersionService.getByAppIdBatch(appIdList);
    //
    //     // 忽略已添加的组件
    //
    //     return ResultJson.success(componentVersionList);
    // }

    /**
     * 逻辑删除
     * @param opsComponentVersionId 主键
     * @return
     */
    @IdempotentSingle
    @PostMapping("delOpsComponentVersion")
    public ResultJson delOpsComponentVersion(String opsComponentVersionId){
        if (CheckTool.checkNull(opsComponentVersionId)){
            return ResultJson.errorCheck();
        }

        OpsComponentVersion opsComponentVersion = opsComponentVersionService.getById(opsComponentVersionId);
        if (opsComponentVersion == null){
            return ResultJson.success();
        }

        // 要删的图片信息
        // List<String> list = new ArrayList<>();
        // List<String> installList = dromaraFileStorageService.getMarkdownImagesUrl(opsComponentVersion.getInstallDoc());
        // if (CollUtil.isNotEmpty(installList)){
        //     list.addAll(installList);
        // }
        // List<String> startList = dromaraFileStorageService.getMarkdownImagesUrl(opsComponentVersion.getStart());
        // if (CollUtil.isNotEmpty(startList)){
        //     list.addAll(startList);
        // }
        // List<String> stopList = dromaraFileStorageService.getMarkdownImagesUrl(opsComponentVersion.getStop());
        // if (CollUtil.isNotEmpty(stopList)){
        //     list.addAll(stopList);
        // }

        List<DromaraFileStorage> bindList = dromaraFileStorageService.getByBindId(opsComponentVersionId);

        opsComponentVersionService.delOpsComponentVersion(opsComponentVersion, bindList);
        return ResultJson.success();
    }

    /**
     * 分页查询
     * @param query 查询参数
     * @return
     */
    @RequestMapping("getOpsComponentVersionPageList")
    public ResultJson getOpsComponentVersionPageList(@Validated OpsComponentVersionQo query){
        if (query == null){
            query = new OpsComponentVersionQo();
        }
        Page page = query.getPage();
        return ResultJson.success(opsComponentVersionService.getOpsComponentVersionPageList(page, query));
    }

    /**
     * 保存
     * @param opsComponentVersion 保存对象
     * @return
     */
    @IdempotentSingle
    @PostMapping("saveOpsComponentVersion")
    public ResultJson saveOpsComponentVersion(@Validated(AddGroup.class) OpsComponentVersion opsComponentVersion){
        String msg = checkOpsComponentVersion(opsComponentVersion);
        if (msg != null){
            return ResultJson.error(msg);
        }

        // 旧的主版本
        OpsComponentVersion oldMainVersion = getOldMainVersion(opsComponentVersion);

        opsComponentVersion.setId(IdTool.getId());
        EntityTool.saveBase(opsComponentVersion);

        // 提取Markdown的数据
        List<DromaraFileStorage> list = getMarkdownImage(opsComponentVersion);

        opsComponentVersionService.saveOpsComponentVersion(opsComponentVersion, oldMainVersion, list);
        return ResultJson.success(opsComponentVersion);
    }

    /**
     * 更新
     * @param opsComponentVersion 更新对象
     * @return
     */
    @IdempotentSingle
    @PostMapping("updOpsComponentVersion")
    public ResultJson updOpsComponentVersion(@Validated(UpdGroup.class) OpsComponentVersion opsComponentVersion){
        String msg = checkOpsComponentVersion(opsComponentVersion);
        if (msg != null){
            return ResultJson.error(msg);
        }

        OpsComponentVersion oldMainVersion = getOldMainVersion(opsComponentVersion);

        // 提取Markdown的数据
        // 修改的时候也要提取，然后转换为生产的数据，这里要注意的是，修改的时候，不考虑去删除旧的数据的问题，到时候删除的时候，直接使用objId统一处理即可，因为这个数据量还是比较小的，没必要找的旧的去删，新的去加，搞麻烦了
        List<DromaraFileStorage> list = getMarkdownImage(opsComponentVersion);

        EntityTool.updBase(opsComponentVersion);
        opsComponentVersionService.updOpsComponentVersion(opsComponentVersion, oldMainVersion, list);
        return ResultJson.success(opsComponentVersion);
    }

    /**
     * 获取图片信息
     * @param opsComponentVersion 版本信息
     * @return 提取到的图片信息用于转正式
     */
    private List<DromaraFileStorage> getMarkdownImage(OpsComponentVersion opsComponentVersion){
        List<DromaraFileStorage> list = new ArrayList<>();
        List<DromaraFileStorage> installList = dromaraFileStorageService.getMarkdownImagesUrlToFileStorage(opsComponentVersion.getInstallDoc(), opsComponentVersion.getId(), ConstantBase.FileSourceType.COMPONENT_VERSION);
        if (CollUtil.isNotEmpty(installList)){
            list.addAll(installList);
        }
        List<DromaraFileStorage> startList = dromaraFileStorageService.getMarkdownImagesUrlToFileStorage(opsComponentVersion.getStart(), opsComponentVersion.getId(), ConstantBase.FileSourceType.COMPONENT_VERSION);
        if (CollUtil.isNotEmpty(startList)){
            list.addAll(startList);
        }
        List<DromaraFileStorage> stopList = dromaraFileStorageService.getMarkdownImagesUrlToFileStorage(opsComponentVersion.getStop(), opsComponentVersion.getId(), ConstantBase.FileSourceType.COMPONENT_VERSION);
        if (CollUtil.isNotEmpty(stopList)){
            list.addAll(stopList);
        }

        return list;
    }

    /**
     * 获取旧的版本并将旧版本设置为普通版本
     * @param opsComponentVersion 新的版本
     * @return
     */
    private OpsComponentVersion getOldMainVersion(OpsComponentVersion opsComponentVersion){
        if (ConstantBase.ComponentVersionType.MAIN.equals(opsComponentVersion.getType())){
            // 检查是否已经有了主版本，将这个版本设置为初始版本，主版本只能有一个
            List<OpsComponentVersion> dbTypeList = opsComponentVersionService.getByTypeFilterId(opsComponentVersion.getComponentId(), opsComponentVersion.getType(), opsComponentVersion.getId());
            if (CollUtil.isNotEmpty(dbTypeList)){
                OpsComponentVersion old = dbTypeList.get(0);
                old.setType(ConstantBase.ComponentVersionType.GENERAL);
                return old;
            }
        }

        return null;
    }

    /**
     * 检查
     * @param opsComponentVersion 校验对象
     * @return 非null则有异常
     */
    private String checkOpsComponentVersion(OpsComponentVersion opsComponentVersion){
        OpsComponentVersion dbVersion = opsComponentVersionService.getByVersionFilterId(opsComponentVersion.getComponentId(), opsComponentVersion.getVersion(), opsComponentVersion.getId());
        if (dbVersion != null){
            return "版本已存在，请勿重复注册";
        }

        return null;
    }
}

